package com.goldman.aplt.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class PropertyUtils {

    /**
     * 获取对象的属性值
     * @param obj 对象
     * @param propertyName 属性名
     * @return 属性值
     * @throws Exception 反射异常
     */
    public static Object getProperty(Object obj, String propertyName) throws Exception {
        if (obj == null) {
            throw new IllegalArgumentException("对象不能为null");
        }
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, obj.getClass());
        Method readMethod = pd.getReadMethod();
        return readMethod.invoke(obj);
    }

    /**
     * 设置对象的属性值
     * @param obj 对象
     * @param propertyName 属性名
     * @param value 属性值
     * @throws Exception 反射异常
     */
    public static void setProperty(Object obj, String propertyName, Object value) throws Exception {
        if (obj == null) {
            throw new IllegalArgumentException("对象不能为null");
        }
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, obj.getClass());
        Method writeMethod = pd.getWriteMethod();
        writeMethod.invoke(obj, value);
    }

    /**
     * 获取对象的所有属性名
     * @param obj 对象
     * @return 属性名数组
     */
    public static String[] getPropertyNames(Object obj) throws IntrospectionException {
        if (obj == null) {
            throw new IllegalArgumentException("对象不能为null");
        }
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        String[] propertyNames = new String[propertyDescriptors.length];
        for (int i = 0; i < propertyDescriptors.length; i++) {
            propertyNames[i] = propertyDescriptors[i].getName();
        }
        return propertyNames;
    }
}